package name.zeno.qrcode

import android.graphics.BitmapFactory
import android.graphics.Color
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.util.Log
import kotlinx.android.synthetic.main.activity_main.*
import name.zeno.qrcode.library.QRCode
import name.zeno.qrcode.library.hui.DrawOptions
import name.zeno.qrcode.library.hui.QrCodeOptions
import name.zeno.qrcode.library.hui.QrCodeUtil
import name.zeno.qrcode.library.hui.style.DrawStyle
import name.zeno.qrcode.library.qrcodeFromAlbum
import name.zeno.qrcode.library.navQrcode

/**
 * 二维码生成
 */
class MainActivity : AppCompatActivity() {


  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    btn_generate.setOnClickListener { generateQrV2() }
    btnQrFromAlbum.setOnClickListener { qrFromAlbum() }
    btn_read.setOnClickListener {
      navQrcode { _, data -> if (data != null) onResult(data) }
    }
  }

  private fun onResult(data: QRCode) {
    et_content.setText(data.data)
    Log.w("FROM", "${data.from}")
    generateQrV2()
  }

  private fun generateQrV2() {
    val msg = et_content.text.toString().trim { it <= ' ' }
    val config = QrCodeOptions(msg = msg, w = 400)
        .logo(
            logo = BitmapFactory.decodeResource(resources, R.drawable.avatar),
            bgColor = Color.WHITE,
            borderColor = Color.LTGRAY,
            round = 24
        )
        .detect(BitmapFactory.decodeResource(resources, R.mipmap.eyes))
        .detect(Color.RED, Color.BLACK)

    config.drawOptions.drawStyle = DrawStyle.sexangle()

    val bmp = QrCodeUtil.toBitmap(config)
    iv_qrcode.setImageBitmap(bmp)
  }


  //  识别图片二维码
  private fun qrFromAlbum() {
    qrcodeFromAlbum().subscribe({ data ->
      et_content.setText(data)
      generateQrV2()
    }, { e ->
      et_content.setText(e.message)
      generateQrV2()
    })
  }
}
